<?php

/**
 * EmsPortal form.
 *
 * @package    ems1
 * @subpackage form
 * @author     Your name here
 * @version    SVN: $Id: sfDoctrineFormTemplate.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class EmsPortalForm extends BaseEmsPortalForm
{
    private static $nums = array(
        3 => 3,
        4 => 4,
        5 => 5,
        6 => 6,
        7 => 7,
        8 => 8,
        9 => 9,
        10 => 10,
    );


    public function configure()
    {
        unset(
            $this['created_at'], $this['updated_at']
        );

        $this->widgetSchema['slug'] = new sfWidgetFormInputHidden();

        if(sfContext::hasInstance('backoffice')){
            unset($this['can_be_accessed_by_list']);
        } else {
            $this->widgetSchema['can_be_accessed_by_list']->setOption('renderer_class', 'sfWidgetFormSelectDoubleList');
        }

        $user = sfContext::getInstance()->getUser();

        if($user->hasCredential('Publicar portal')){
            $this->widgetSchema['published'] = new sfWidgetFormChoice(array(
                'label'    => 'Publicar',
                'choices'  => Doctrine_Core::getTable('EmsPortal')->getbooleanOptions(),
                'multiple' => false,
                'expanded' => true,
            ));

            $this->validatorSchema['published'] = new sfValidatorChoice(array(
                'choices' => array_keys(Doctrine_Core::getTable('EmsPortal')->getbooleanOptions()),
            ));
        } else {
            unset($this['published']);
        }

        if($user->hasCredential('Habilitar portal') && $this->getObject()->exists()){
            $this->widgetSchema['is_enabled'] = new sfWidgetFormChoice(array(
                'label'    => 'Habilitar',
                'choices'  => Doctrine_Core::getTable('EmsPortal')->getbooleanOptions(),
                'multiple' => false,
                'expanded' => true,
            ));

            $this->validatorSchema['is_enabled'] = new sfValidatorChoice(array(
                'choices' => array_keys(Doctrine_Core::getTable('EmsPortal')->getbooleanOptions()),
            ));
        } else {
            unset($this['is_enabled']);
        }

        $this->validatorSchema['title']->setMessages(array(
            'max_length' => 'El nombre "%value%" excede el limite de caracteres (máximo %max_length% caracteres).',
            'required' => 'Campo obligatorio, debe indicar el nombre del portal.'
            ));

        $this->widgetSchema->setHelp('email', 'Por ejemplo: correo@ejemplo.com');

        $this->validatorSchema['email'] = new sfValidatorEmail(
                array(
                    'max_length' => 255,
                    'trim' => true,
                    ), array(
                    'max_length' => 'La dirección "%value%" excede el limite de caracteres (máximo %max_length% caracteres).',
                    'invalid'    => 'La dirección "%value%" no tiene el formato de correo electrónico válido.',
                    'required'   => 'Campo obligatorio, debe indicar una dirección de correo electrónico.'
                ));

        $this->widgetSchema->setHelp('website_url', 'Por ejemplo: http://www.ejemplo.com');
        
        $this->validatorSchema['website_url'] = new sfValidatorUrl(
                array(
                    'max_length' => 255,
                    'trim'       => true,
                    'required'   => false
                ), array(
                    'max_length' => 'La dirección "%value%" excede el limite de caracteres (máximo %max_length% caracteres).',
                    'invalid'    => 'La dirección "%value%" no tiene el formato de URL válido.'
                ));

        $this->widgetSchema['downloadable_contents_preview'] = new sfWidgetFormChoice(array(
            'choices'  => Doctrine_Core::getTable('EmsPortal')->getBooleanOptions(),
            'multiple' => false,
            'expanded' => true,
        ));

        $this->validatorSchema['downloadable_contents_preview'] = new sfValidatorChoice(array(
            'choices' => array_keys(Doctrine_Core::getTable('EmsPortal')->getbooleanOptions()),
        ));

        $this->setWidget('image', new sfWidgetFormInputHidden());

        $this->setValidator('image',new sfValidatorString(array('required' => false)));

        $this->setWidget('image_type', new sfWidgetFormInputHidden());

        $this->setValidator('image_type',new sfValidatorString(array('max_length' => 100, 'required' => false)));

        $this->setWidget('image_size', new sfWidgetFormInputHidden());

        $this->setValidator('image_size',new sfValidatorInteger(array('required' => false)));

        $this->setWidget('tmp_image', new sfWidgetFormInputFile());

        $this->setValidator('tmp_image',new sfValidatorString(array('required' => false)));
        
        if($this->getObject()->exists() && $this->getObject()->getImage()){
            $image = $this->getObject()->getImage();

            $folder = sfConfig::get('sf_upload_dir').'/portal_'.$this->getOption('portal_id').'/images/';

            if(is_file($folder.$image)){
                $image_size = imagesize($folder.$image);

                $this->setDefaults(array('image_size' => $image_size));
            } else {
                $this->setDefaults(array('image_size' => 0));
            }
        }

        $this->widgetSchema['max_comments_per_page'] = new sfWidgetFormChoice(array(
            'choices'  => self::$nums,
            'multiple' => false,
            'expanded' => false,
        ));

        $this->validatorSchema['max_comments_per_page'] = new sfValidatorChoice(array(
            'choices' => array_keys(self::$nums),
        ));

        $this->widgetSchema['uses_register'] = new sfWidgetFormChoice(array(
            'choices'  => Doctrine_Core::getTable('EmsPortal')->getbooleanOptions(),
            'multiple' => false,
            'expanded' => true,
        ));

        $this->validatorSchema['uses_register'] = new sfValidatorChoice(array(
            'choices' => array_keys(Doctrine_Core::getTable('EmsPortal')->getbooleanOptions()),
        ));

        $this->widgetSchema['uses_serv_buttons'] = new sfWidgetFormChoice(array(
            'choices'  => Doctrine_Core::getTable('EmsPortal')->getbooleanOptions(),
            'multiple' => false,
            'expanded' => true,
        ));

        $this->validatorSchema['uses_serv_buttons'] = new sfValidatorChoice(array(
            'choices' => array_keys(Doctrine_Core::getTable('EmsPortal')->getbooleanOptions()),
        ));

        $this->widgetSchema['uses_content_comments'] = new sfWidgetFormChoice(array(
            'choices'  => Doctrine_Core::getTable('EmsPortal')->getbooleanOptions(),
            'multiple' => false,
            'expanded' => true,
        ));

        $this->validatorSchema['uses_content_comments'] = new sfValidatorChoice(array(
            'choices' => array_keys(Doctrine_Core::getTable('EmsPortal')->getbooleanOptions()),
        ));

        $this->widgetSchema->setLabels(array(
            'title'                 => 'Nombre',
            'email'                 => 'Correo electrónico',
            'tmp_image'             => 'Imagen',
            'organization_id'       => 'Organización',
            'uses_register'         => 'Con registro',
            'uses_serv_buttons'     => 'Con botones de servicio',
            'uses_content_comments' => 'Con comentarios sobre contenidos',
            'max_comments_per_page' => 'Comentarios por página',
            'website_url'           => 'URL del sitio Web tradicional',
            'downloadable_contents_preview' => 'Contenidos descargables con vista previa'
        ));

        if ($this->getObject()->exists())
        {
            unset ($this['organization_id']);
        }

        $this->validatorSchema->setPostValidator(
                new sfValidatorAnd(array(
                    new sfValidatorDoctrineUnique(
                            array('model' => 'EmsPortal', 'column' => array('title')),
                            array('invalid' => 'Ya existe un portal con mismo nombre.')
                    ),
                    new sfValidatorDoctrineUnique(
                            array('model' => 'EmsPortal', 'column' => array('slug')),
                            array('invalid' => 'Ya existe un portal con mismo nombre.')
                    ))
                ));
    }

    public function bind(array $taintedValues = null, array $taintedFiles = null)
    {
        $taintedValues['slug'] = '';

        parent::bind($taintedValues, $taintedFiles);
    }

    protected function doUpdateObject($values)
    {
        if(strcasecmp($values['image'],'') != 0){

            $path_parts_image = pathinfo($values['image']);

            if ($this->getObject()->exists()){
                $folder = sfConfig::get('sf_upload_dir').'/portal_'.$this->getObject()->getId().'/images/';
            } else {
                $folder = sfConfig::get('sf_upload_dir').'/temp_files';
            }

            if(!$this->getObject()->exists() || strcasecmp($path_parts_image['basename'], $this->getObject()->getImage()) != 0){
                $values['image'] =  $this->saveUploadedFile(
                                        $path_parts_image['basename'],
                                        $values['image_type'],
                                        $values['image'],
                                        $values['image_size'],
                                        $folder
                                    );
            }
        }

        unset(
            $values['image_type'], $values['image_size'], $values['tmp_image']
        );

        parent::doUpdateObject($values);
    }

    protected function saveUploadedFile($originalName, $type, $tempName, $size, $path) {

        $validated_file = new sfValidatedFile($originalName, $type, $tempName, $size, $path);

        return $validated_file->save();
    }

    public function save($con = null){
        $exists = $this->getObject()->exists();

        $portal = parent::save($con);

        if(!$exists){
            mkdir(sfConfig::get('sf_upload_dir').'/portal_'.$portal->getId());
            mkdir(sfConfig::get('sf_upload_dir').'/portal_'.$portal->getId().'/images');
            mkdir(sfConfig::get('sf_upload_dir').'/portal_'.$portal->getId().'/sounds');
            mkdir(sfConfig::get('sf_upload_dir').'/portal_'.$portal->getId().'/videos');
            mkdir(sfConfig::get('sf_upload_dir').'/portal_'.$portal->getId().'/temp_files');
            mkdir(sfConfig::get('sf_upload_dir').'/portal_'.$portal->getId().'/css');
        }

        if(!$exists && $portal->getImage()){
            copy(sfConfig::get('sf_upload_dir').'/temp_files/'.$portal->getImage(),
                    sfConfig::get('sf_upload_dir').'/portal_'.$portal->getId().'/images/'.$portal->getImage());

            unlink(sfConfig::get('sf_upload_dir').'/temp_files/'.$portal->getImage());
        }

        return $portal;
    }
}
